package com.jojo.jojomall.product.web;

import com.jojo.jojomall.product.entity.CategoryEntity;
import com.jojo.jojomall.product.service.CategoryService;
import com.jojo.jojomall.product.vo.Catelog2Vo;
import org.redisson.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @Author: 魔法少女小夫
 * @Data: 2022/5/12
 * @Version:
 * @Description:
 */
@Controller
public class IndexController {
    @Autowired
    RedissonClient redissonClient;
    @Autowired
    CategoryService categoryService;


    @Autowired
    StringRedisTemplate redisTemplate;

    @GetMapping(value = {"/", "/index.html"})
    public String indexPage(Model model) {
//        查出所有一级分类
        List<CategoryEntity> Cats = categoryService.getLevel1Categorys();
        model.addAttribute("categorys", Cats);
        return "item";
    }

    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        Map<String, List<Catelog2Vo>> map = categoryService.getCatalogJson();
        return map;
    }

    @ResponseBody
    @RequestMapping("/hello")
    public String HelloTest() {
//        获取一把锁只要名字一样，就是同一把锁
        RLock lock = redissonClient.getLock("牛牛lock");
        try {
            System.out.println("加锁成功，执行业务");
            Thread.sleep(3000);
        } catch (Exception e) {
            throw new RuntimeException();
        } finally {
            System.out.println("释放锁,线程名字为" + Thread.currentThread().getId());
            lock.unlock();
        }


        return "hello";
    }

    @ResponseBody
    @GetMapping("/write")
    public String writeLog() {
        String s = "";
        RReadWriteLock rwlock = redissonClient.getReadWriteLock("rw-lock");
        RLock wlock = rwlock.writeLock();
        try {
        wlock.lock();
            System.out.println("写锁加锁完成");
            s = UUID.randomUUID().toString();
            Thread.sleep(30000);
            redisTemplate.opsForValue().set("writeBody", s);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            System.out.println("写锁解锁成功");
            wlock.unlock();
        }


        return s;

    }


    @ResponseBody
    @GetMapping("/read")
    public String readLog() {
        RReadWriteLock rwlock = redissonClient.getReadWriteLock("rw-lock");
        String s = "";
        RLock rLock = rwlock.readLock();
        try {
            rLock.lock();
            System.out.println("读锁加锁完成");
            s = redisTemplate.opsForValue().get("writeBody");
//            TimeUnit.SECONDS.sleep(30);
            Thread.sleep(10000);
        } catch (Exception e) {
            System.out.println(e);
        } finally {
            System.out.println("读锁解锁成功");
            rLock.unlock();
        }
        System.out.println(s);
        return s;

    }
//    闭锁实验：
    @GetMapping("/lockDoor")
    @ResponseBody
    public String lockDoor() throws InterruptedException {
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.trySetCount(5);
        System.out.println("正在等待锁门,还有"+door.getCount()+"个班没走");
//        等待闭锁完成
        door.await();
        return "放假了，给我锁";
    }




    @GetMapping("/gogo/{id}")
    @ResponseBody
    public String gogogo(@PathVariable("id") Long id){
        RCountDownLatch door = redissonClient.getCountDownLatch("door");
        door.countDown();/*计数减一；*/
        return id+"班的人走了";
    }



//    信号量：Semaphore
    /*使用车库停车展示信号量的用法*/
    @GetMapping("/park")
    @ResponseBody
    public String park() throws InterruptedException {
//        获取到这个信号量
        RSemaphore park = redissonClient.getSemaphore("park");
//        获取一个信号；获取一个值
//        park.acquire();/*相当于拿一个车位出来*/
        boolean b = park.tryAcquire();//能泊车就泊车不能泊就算了 不等待，且会返回是否泊车了
//        这里根据信号量返回的值可以轻松进行业务操作；
//        信号量 Semaphore :可以用来限流
        if (b){
//            执行业务
        }else {
//        限制
        }
        return "ok，车位"+b+"泊车";
    }
    @GetMapping("/go")
    @ResponseBody
    public String go() throws InterruptedException {
//        获取到这个信号量
        RSemaphore park = redissonClient.getSemaphore("park");
//        获取一个信号；获取一个值
        park.release();//释放一个车位
        return "ok，您已成功驶出，车位释放";
    }
}

